package cn.sstech.IM.server.group;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.sstech.IM.server.model.BroadcastGroup;
import cn.sstech.IM.webserver.user.model.UserInfoEntity;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.ChannelGroupFuture;
import io.netty.channel.group.ChannelMatcher;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

public class BroadcastGroupManager {
	
	/**
	 * 初始化系統廣播群 (未完成)
	 */
	public void init(){
		
	}

	static Logger logger = LoggerFactory.getLogger(ServerGroupManager.class);
	
	private static final Map<Long,BroadcastGroup> BROADCAST_GROUP = new HashMap<Long,BroadcastGroup>();
	
	/**
	 * 根据群的数据库id查找群对象
	 * @param groupId
	 * @return
	 */
	public static ChannelGroup getGroup(Long groupId ,UserInfoEntity manager){
		ChannelGroup channelGroup = BROADCAST_GROUP.get(groupId).getChannelGroup();
		if(null == channelGroup && null != groupId && manager!=null){
			channelGroup = new DefaultChannelGroup(String.valueOf(groupId), GlobalEventExecutor.INSTANCE);
			BroadcastGroup broadcastGroup = new BroadcastGroup();
			broadcastGroup.setId(groupId);
			broadcastGroup.setChannelGroup(channelGroup);
			broadcastGroup.setManager(manager);
			BROADCAST_GROUP.put(groupId, broadcastGroup);
		}
		
		return channelGroup;
	}
	
    public static void addChannel(Channel channel,Long groupId ) {
    	if(null != BROADCAST_GROUP.get(groupId)){
    		BROADCAST_GROUP.get(groupId).getChannelGroup().add(channel);
    	}
    	else{
    		logger.warn(String.valueOf(groupId)+"群组不存在，无法添加channel");
    	}
    	
    }
	
    /**
     * 广播 
     * @param msg
     * @return
     */
    public static ChannelGroupFuture broadcast(Object msg,Long groupId) {
    	ChannelGroup channelGroup = BROADCAST_GROUP.get(groupId).getChannelGroup();
    	if(null != channelGroup){
    		return channelGroup.writeAndFlush(msg);
    	}
    	else{
    		logger.warn(String.valueOf(groupId)+"群组不存在，无法广播");
    		return null;
    	}
    }
    /**
     * 广播
     * @param msg
     * @param matcher
     * @return
     */
    public static ChannelGroupFuture broadcast(Object msg, ChannelMatcher matcher,Long groupId) {
    	ChannelGroup channelGroup = BROADCAST_GROUP.get(groupId).getChannelGroup();
    	if(null != channelGroup){
    		return channelGroup.writeAndFlush(msg, matcher);
    	}
    	else{
    		logger.warn(String.valueOf(groupId)+"群组不存在，无法广播");
    		return null;
    	}
    }
}
